import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { useLocalStorage } from '@vueuse/core';

export const request = axios.create({
  baseURL: 'http://127.0.0.1:9090',
  timeout: 5000, // 超时设置为5秒
});

export const token = useLocalStorage('token', '');  //把token存储到localstore
export const menu_permission = useLocalStorage('menu_permission', {}) //把菜单权限存储到localstore，用来判断是否显示菜单
export const actions = useLocalStorage('actions', []) //把操作按钮权限放localstore，用来判断是否显示操作按钮
// Add a request interceptor
request.interceptors.request.use(function (config) {
  // Do something before request is sent
  if (token.value !== '') {
    config.headers.Authorization = `Bearer ${token.value}`
  }
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

// Add a response interceptor
request.interceptors.response.use(function (response) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  console.log(response);

  return response;
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  if (error.response && error.response.status === 401) {
    ElMessage.error('未授权，请重新登录');
    token.value = '';
    menu_permission.value = {};
    actions.value = [];
    router.push('/login');
  }
  return Promise.reject(error);
});

